package com.juc.future;

import java.util.concurrent.*;

/**
 * @Author HK
 * @Date 2022/5/14 16:32
 * @Version 1.0
 */
public class CompletableFutureDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 20
                , 1L, TimeUnit.SECONDS
                , new LinkedBlockingDeque<>(50)
                , Executors.defaultThreadFactory()
                , new ThreadPoolExecutor.AbortPolicy());
        /**
         * runAsync:无返回值
         * supplyAsync:有返回值
         *
         * join和get可以直接返回结构
         */

        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 13;
        }).thenApply(f ->{
            return f + 2;
        }).whenComplete((success, error) ->{
            if (error == null){
                System.out.println("result:"+ success);
            }
        }).exceptionally(e ->{
            e.printStackTrace();
            return null;
        });

        m2();
        System.out.println("不要阻塞我，因为我是主线程，不能停止！！");

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        threadPoolExecutor.shutdown();
    }

    /**
     * 对结果进行合并
     *  比如：合并两个接口内容数据返回前端
     */
    private static void m2(){
        Integer join = CompletableFuture.supplyAsync(() -> {
            return 12;
        }).thenCombine(CompletableFuture.supplyAsync(() -> {
            return 13;
        }), (r1, r2) -> {
            return r1 + r2;
        }).join();
        System.out.println(join);
    }

    private static void m1() throws ExecutionException, InterruptedException {

        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            System.out.println("come on....");
        });

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("come on....");
            return 2;
        });

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 20
                , 1L, TimeUnit.SECONDS
                , new LinkedBlockingDeque<>(50)
                , Executors.defaultThreadFactory()
                , new ThreadPoolExecutor.AbortPolicy());

        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
            System.out.println("come on......");
            return 17;
        }, threadPoolExecutor);
        threadPoolExecutor.shutdown();

        CompletableFuture<Integer> future4 = CompletableFuture.supplyAsync(() -> {
            System.out.println("come on......");
            return 13;
        }, threadPoolExecutor);
        threadPoolExecutor.shutdown();
        System.out.println(future4.get());
    }


}
